package cn.echo.sharding.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;


/**
 * 按旬拆表方式
 * @author lonyee
 *
 */
public class TendaysPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {
	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
		String shardfix = this.getShardfix(shardingValue.getValue());
        for (String each : availableTargetNames) {	
            if (each.endsWith(shardfix)) {
                return each;
            }
        }
        throw new UnsupportedOperationException();
	}
	
	 //按旬拆表
    private String getShardfix(Date date) {
    	Calendar calendar = Calendar.getInstance();
 		calendar.setTime(date);
 		String shardfix = ""+ calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1);
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
 		if (day<=10) {
 			shardfix +="01";
 		} else if (day<=20) {
 			shardfix +="02";
 		} else {
 			shardfix +="03";
 		}
 		return shardfix;
    }
}
